package com.carnation._executor;


import lombok.Data;

import java.util.concurrent.*;

/**
 * <p>
 * Runnable、Callable、Future、FutureTask
 * </p>
 *
 * @author: Sunny
 * @date: 2021/2/1
 * @version: v1.0.0
 */
public class TaskTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1：单线程 + Callable + FutureTask拿到返回结果
        FutureTask<Integer> task = new FutureTask<Integer>(() -> {
            return 1 + 1;
        });
        Thread t1 = new Thread(task);
        t1.start();
        System.out.println(task.get());

        // 2：单线程 + Runnable + T result + FutureTask拿到返回结果
        Account account = new Account();
        FutureTask<Account> task1 = new FutureTask<Account>(() -> {
            account.setName("zhangsan");
            account.setAge(3);
        }, account);
        Thread t2 = new Thread(task1);
        t2.start();
        System.out.println(task1.get().getName() + " : " + task1.get().getAge());
        System.out.println(account.getName() + " : " + account.getAge());

        // 3：线程池 + Callable + Future拿到返回结果
        ExecutorService service = Executors.newSingleThreadExecutor();
        Future<Integer> future = service.submit(() -> 1 + 1);
        System.out.println(future.get());

        // 4：线程池 + Runnable + Future拿不到返回结果
        Future<?> future1 = service.submit(() -> System.out.println(1));
        // Runnable 不接受返回值，因此其值为null
        System.out.println(future1.get());

        // 5：线程池 + Runnable +  T result + Future拿到返回结果
        Account account1 = new Account();
        Future<Account> future2 = service.submit(() -> {
            account1.setName("xiaoming");
            account1.setAge(4);
        }, account1);
        System.out.println(future2.get().getName() + " : " + future2.get().getAge());
        System.out.println(account1.getName() + " : " + account1.getAge());
        service.shutdown();
    }

    @Data
    public static class Account {
        private String name;
        private Integer age;
    }

}
